package com.hc.javabasestudyproject.juc.aqs.tools;

import lombok.SneakyThrows;

import java.util.concurrent.CountDownLatch;

/**
 * @Author: huangcheng
 * @CreateTime: 2024-04-09  16:44
 * @Description: 主线程等待10个子线程执行完毕
 * @Version: 1.0
 */
public class CountDownLatchTest {

    public static void main(String[] args) throws InterruptedException {
        // 采用 10 个工作线程去执行任务
        final int threadCount = 10;
        CountDownLatch countDownLatch = new CountDownLatch(threadCount);
        for (int i = 0; i < threadCount; i++) {
            new Thread(new Runnable() {
                @Override
                @SneakyThrows
                public void run() {
                    // 执行具体任务
                    System.out.println("thread name:" +  Thread.currentThread().getName() + "，执行完毕！");
                    // 计数器减 1
                    countDownLatch.countDown();
                    Thread.sleep(1000);
                    System.out.println("thread name:" +  Thread.currentThread().getName() + "，执行完毕！");
                }
            }).start();
        }

        // 阻塞等待 10 个工作线程执行完毕
        countDownLatch.await();
        System.out.println("所有任务线程已执行完毕，准备进行结果汇总");
    }
}
